package cn.chrilwe.pigpig.im.scaner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;

import cn.chrilwe.pigpig.im.Main;
/**
  * 类扫描器
 * @author chrilwe
 * 2020-7-28
 */
public class ClassScanner {

	public static List<String> scan(String packages) throws IOException {
		String[] split = packages.split("[.]");
		String filePath = "";
		for(int i=0; i<split.length; i++) {
			filePath += split[i] + "/";
		}
		
		return doScan(filePath);
	}
	
	
	protected static List<String> doScan(String filePath) throws IOException {
		ResourcePatternResolver resolver =new PathMatchingResourcePatternResolver();
		MetadataReaderFactory metaReader = new CachingMetadataReaderFactory(resolver);
		Resource[] resources = resolver.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+ filePath +"**/*.class");
		
		List<String> classNames = new ArrayList<String>();
		for (Resource resource : resources) {
			MetadataReader metadataReader = metaReader.getMetadataReader(resource);
			String className = metadataReader.getClassMetadata().getClassName();
			classNames.add(className);
		}
		return classNames;
	}
}
